#!/bin/bash

# 下载或更新
cloneOrPull() {
    GIT_URL=$1
    TARGET_DIR=$2
    if [ "$TARGET_DIR" == "" ]; then
        var1=${GIT_URL##*/}
        TARGET_DIR=${var1%.*}
    fi
    echo "GIT_URL=$GIT_URL"
    echo "TARGET_DIR=$TARGET_DIR"
    if [ ! -d "$TARGET_DIR/.git" ] || [ "$(git -C $TARGET_DIR status -s)" != "" ]; then
        rm -rf $TARGET_DIR
        mkdir -p $TARGET_DIR
        git clone $GIT_URL $TARGET_DIR
    else
        git -C $TARGET_DIR pull
    fi
}

function set_hos_sdk_api11() {
    echo "set_hos_sdk_api11"
    # 下载 harmonyos-next-dp1
    if [ -f "harmonyos-next-dp1-linux-x64.zip" ]; then
        echo "harmonyos-next-dp1-linux-x64.zip已存在，不重复下载"
    else
        echo "Start download harmonyos-next-dp1-linux-x64.zip ..."
        curl -o harmonyos-next-dp1-linux-x64.zip https://update.dbankcdn.com/download/data/pub_13/HWHOTA_hota_900_9/71/v3/-BVBXAvxQdiDZI9X8DpPJg/harmonyos-next-dp1-linux-x64.zip
    fi
    if [ $? != 0 ]; then
        echo "Download harmonyos-next-dp1-linux-x64.zip failed."
        rm -rf harmonyos-next-dp1-linux-x64.zip
    fi

    rm -rf new-os-sdk
    mkdir new-os-sdk

    if [ ! -d "new-os-sdk/HarmonyOS-NEXT-DP1" ]; then
        # 解压HarmonyOS NEXT DP1 SDK
        echo "start to unzip harmonyos-next-dp1-linux-x64.zip."
        unzip -q harmonyos-next-dp1-linux-x64.zip -d new-os-sdk/HarmonyOS-NEXT-DP1
        ls new-os-sdk/HarmonyOS-NEXT-DP1
        echo "unzip harmonyos-next-dp1-linux-x64.zip success."
    fi
}

function set_hos_sdk_api12() {
    echo "set_hos_sdk_api12"
    # 下载 HarmonyOS SDK
    cloneOrPull https://gitee.com/lihui868/new-os-sdk12.git
    sdk_last=ohos_sdk_20240820_020224.tar.gz
    sdk_name=ohos_sdk_20241008_020250.tar.gz

    rm $sdk_last
    if [ -f "$sdk_name" ]; then
        echo "File $sdk_name exists, do not download again."
    else
        echo "Start downloading $sdk_name"
        curl -o $sdk_name https://cidownload.openharmony.cn/version/Master_Version/OpenHarmony_5.0.2.43/20241008_020250/version-Master_Version-OpenHarmony_5.0.2.43-20241008_020250-ohos-sdk-full.tar.gz
    fi
    if [ $? != 0 ]; then
        echo "Download $sdk_name failed."
        rm -rf $sdk_name
    fi

    echo "Start unzip ohos_sdk."
    rm -rf new-os-sdk && rm -rf ohos-sdk
    mkdir new-os-sdk
    mkdir ohos-sdk
    tar -xf $sdk_name -C ohos-sdk/
    mkdir -p ohos-sdk/openharmony && find ohos-sdk/linux/ -name "*.zip" -exec unzip -q {} -d ohos-sdk/openharmony/ \;
    cp -r new-os-sdk12/HarmonyOS-NEXT-DB1 new-os-sdk/HarmonyOS-NEXT-DB1
    mv ohos-sdk/openharmony new-os-sdk/HarmonyOS-NEXT-DB1/
    echo "Finish unzip ohos_sdk."
}

if [ "$1" == "12" ]; then
    set_hos_sdk_api12
else
    set_hos_sdk_api11
fi
